'use strict'
$(function () {
    query()
    let id = location.search.split('?')[1]
    if (id) {
        getproduct(id).then(data => {
            $('[name=id]').val(data[0].id)
            $('[name=name]').val(data[0].name)
            $('[name=price]').val(data[0].price)
        })
    }
    
})
function query() {
    let keyword = $('[name=keyword]').val()
    getproduct(keyword).then(data => {
        rendata(data)
    })
}
function rendata(res) {
    let tr = $('.tr')
    tr.remove()
    res.forEach((item,index) => {
        if(index%2==0){
            let html = `
            <tr class="tr" key="${item.id}" style="background-color: beige;" id="row">
            <td>${item.id}</td>
            <td>${item.name}</td>
            <td>${item.price}</td>
            <td>
                <input type="button" name="" id="" value="编辑" onclick="edit(${item.id})">
                <input type="button" name="" id="" value="删除" onclick="del(${item.id})">
            </td>
        </tr>
            `
            $('#tb').append(html)
         
        }else{
            let html = `
            <tr class="tr" key="${item.id}" id="row"  style=" background-color: chartreuse;" >
            <td>${item.id}</td>
            <td>${item.name}</td>
            <td>${item.price}</td>
            <td>
                <input type="button" name="" id="" value="编辑" onclick="edit(${item.id})">
                <input type="button" name="" id="" value="删除" onclick="del(${item.id})">
            </td>
        </tr>
            `
            $('#tb').append(html)
        
        }


    });
    
}
function add() {
    location.href = './addOrEdit.html'
}
function cencel() {
    location.href = './index.html'
}
function save() {
    let id = $('[name=id]').val()
    let name = $('[name=name]').val()
    let price = $('[name=price]').val()
    let obj = {
        id,
        name,
        price
    }
    if (obj.id) {
        putproduct(obj, obj.id).then(data => {
            if (data.code == 1000) {
                location.href = './index.html'
            } else {
                alert('gg')
            }
        })
    } else {
        postproduct(obj).then(data => {
            if (data.code == 1000) {
                location.href = './index.html'
            } else {
                alert('gg')
            }
        })
    }
}
function edit(id) {
    location.href = `./addOrEdit.html?${id}`
}
function del(id) {
    if (confirm(`确认删除${id}`)) {
        delproduct(id).then(data => {
            let id = data.data.id
            $(`[key=${id}]`).remove()
        })
    }
}